<template>
  <uni-data-select
    v-model="localValue"
    :localdata="dictOptions"
    :clear="clear"
    :placeholder="placeholder"
    :disabled="disabled"
    @change="onChange"
  />
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  dictType: {
    type: String,
    required: true
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  clear: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const localValue = ref(props.modelValue)
const dictOptions = ref([])

// 监听 prop 变化
watch(() => props.modelValue, (newVal) => {
  localValue.value = newVal
})

// 加载字典数据
const loadDictData = async () => {
  try {
    const db = uniCloud.database()
    const res = await db.collection('iss-wallpaper-dict')
      .where({
        type: props.dictType,
        status: true,
      })
      .orderBy('sort', 'desc')
      .orderBy('options.sort', 'desc')
      .get()
	
    if (res.result.data && res.result.data.length > 0) {
      const dictItem = res.result.data[0]
      dictOptions.value = dictItem.options
        .filter(option => option.status !== false)
        .map(option => ({
          value: option.code,
          text: option.text,
          description: option.description
        }))
    }
  } catch (e) {
    console.error('加载字典数据失败:', e)
  }
}

// 选择变化事件
const onChange = (code) => {
	emit('update:modelValue', code)
	emit('change', code)
}

// 组件挂载时加载数据
onMounted(() => {
  loadDictData()
})
</script>